# -*- coding:utf-8 -*-
#
#   author: iflytek
#
#  本demo测试时运行的环境为：Windows + Python3.7
#  本demo测试成功运行时所安装的第三方库及其版本如下：
#   cffi==1.12.3
#   gevent==1.4.0
#   greenlet==0.4.15
#   pycparser==2.19
#   six==1.12.0
#   websocket==0.2.1
#   websocket-client==0.56.0
#   合成小语种需要传输小语种文本、使用小语种发音人vcn、ent=mtts、tte=unicode以及修改文本编码方式
#  错误码链接：https://www.xfyun.cn/document/error-code （code返回错误码时必看）
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import base64
import datetime
import hashlib
import hmac
import json
import os
import ssl
from _thread import start_new_thread
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time

import websocket

STATUS_FIRST_FRAME = 0  # 第一帧的标识
STATUS_CONTINUE_FRAME = 1  # 中间帧标识
STATUS_LAST_FRAME = 2  # 最后一帧的标识
APPID = '5ea28c02'
APIKey = '8c7511ed313501ee9a7da9c3d07d22e2'
APISecret = '59c97fa74ef492ee84f91ac78996a030'


class Ws_Param(object):
    # 初始化
    def __init__(self, APPID, APIKey, APISecret, Text):
        self.APPID = APPID
        self.APIKey = APIKey
        self.APISecret = APISecret
        self.Text = Text

        # 公共参数(common)
        self.CommonArgs = {"app_id": self.APPID}
        # 业务参数(business)，更多个性化参数可在官网查看
        self.BusinessArgs = {"aue": "lame", "auf": "audio/L16;rate=16000", "vcn": "x2_yezi", "tte": "utf8",
                             "ent": "aisound", "speed": 50}
        self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}
        # 使用小语种须使用以下方式，此处的unicode指的是 utf16小端的编码方式，即"UTF-16LE"”
        # self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-16')), "UTF8")}

    # 生成url
    def create_url(self):
        url = 'wss://tts-api.xfyun.cn/v2/tts'
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                 digestmod=hashlib.sha256).digest()
        signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
            self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": "ws-api.xfyun.cn"
        }
        # 拼接鉴权参数，生成url
        url = url + '?' + urlencode(v)
        # print("date: ",date)
        # print("v: ",v)
        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释，比对相同参数时生成的url与自己代码生成的url是否一致
        # print('websocket url :', url)
        return url


class KdfxAudioApiWSClient(object):

    def __init__(self, text, mp3_path):
        self.wsParam = Ws_Param(APPID=APPID, APIKey=APIKey, APISecret=APISecret, Text=text)
        self.mp3_path = mp3_path
        ws_url = self.wsParam.create_url()
        self.ws = websocket.WebSocketApp(ws_url, on_message=self.on_message, on_error=self.on_error,
                                         on_close=self.on_close)
        self.ws.on_open = self.on_open

    def to_mp3(self):
        websocket.enableTrace(False)

        self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
        return self.mp3_path

    def on_message(self, message):
        try:
            message = json.loads(message)
            code = message["code"]
            sid = message["sid"]
            audio = message["data"]["audio"]
            audio = base64.b64decode(audio)
            status = message["data"]["status"]
            if status == 2:
                self.ws.close()
            if code != 0:
                errMsg = message["message"]
                print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
            else:
                with open(self.mp3_path, 'ab') as f:
                    f.write(audio)

        except Exception as e:
            print("receive msg,but parse exception:", e)

    # 收到websocket错误的处理
    def on_error(self, error):
        print("### error:", error)

    # 收到websocket关闭的处理
    def on_close(self):
        print("### closed ###")

    # 收到websocket连接建立的处理
    def on_open(self):
        def run(*args):
            d = {"common": self.wsParam.CommonArgs,
                 "business": self.wsParam.BusinessArgs,
                 "data": self.wsParam.Data,
                 }
            d = json.dumps(d)
            self.ws.send(d)

        start_new_thread(run, ())


def text_to_mp3(mp3_path, text):
    """
    新版本的api，解决无法获取完整的音频数据bug
    :param mp3_path: 音频路径
    :param text: 文本内容
    :return:
    """
    if os.path.exists(mp3_path):
        print("mp3 {} has exists will remove".format(mp3_path))
        os.remove(mp3_path)
    client = KdfxAudioApiWSClient(text, mp3_path)
    return client.to_mp3()


# def text_to_mp3(mp3, text):
#     # 测试时候在此处正确填写相关信息即可运行
#     wsParam = Ws_Param(APPID=APPID, APIKey=APIKey, APISecret=APISecret, Text=text)
#     ws = create_connection(wsParam.create_url())
#     # print("Sent")
#     if os.path.exists(mp3):
#         os.remove(mp3)
#     d = {"common": wsParam.CommonArgs,
#          "business": wsParam.BusinessArgs,
#          "data": wsParam.Data,
#          }
#     d = json.dumps(d)
#     ws.send(d)
#     # print("Receiving...")
#     result = ws.recv()
#     print("Received '%s'" % result)
#     message = json.loads(result)
#     code = message["code"]
#     sid = message["sid"]
#     audio = message["data"]["audio"]
#     audio = base64.b64decode(audio)
#     status = message["data"]["status"]
#     if status == 2:
#         print("ws is closed")
#     if code != 0:
#         errMsg = message["message"]
#         print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
#     else:
#         with open(mp3, 'ab') as f:
#             f.write(audio)
#     ws.close()
#     return mp3


if __name__ == "__main__":
    # text_to_mp3('test.mp3',
    #             '异动原因：联创光电高温超导感应加热项目获得业界泰斗肯定 首台设备交付在即')

    # ws = WSClient("异动原因：联创光电高温超导感应加热项目获得业界泰斗肯定 首台设备交付在即", "new_test.mp3")
    target_mp3_path = text_to_mp3("new_test.mp3",
                                  "联创光电（600363）母公司江西省电子集团官网日前披露，国家最高科学技术奖获得者、中国高温超导研究奠基人、中科院院士赵忠贤一行日前赴联创光电考察调研公司高温超导感应加热项目的产业化进程，并按下全球首台兆瓦级高温超导感应加热设备交付前的可靠性测试启动键")
    print(target_mp3_path)
